﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

using Lilium.Collections;
using Lilium.Web.Mvc.State;
using Lilium.Web.Mvc.Validation;
using Lilium.Web.Mvc.Metadata;

namespace Lilium.Web.Mvc.Html
{
    public static class ImageExtensions
    {
        public static MvcHtmlString Image<TController>(this HtmlHelper html, Expression<Func<TController, ActionResult>> action, string alt)
        {
            return ImageExtensions.Image<TController>(html, action, new { alt = alt });
        }

        public static MvcHtmlString Image<TController>(this HtmlHelper htmlHelper, Expression<Func<TController, ActionResult>> action, object htmlAttributes)
        {
            return ImageExtensions.Image<TController>(htmlHelper, action, (IDictionary<string, object>)null, new RouteValueDictionary(htmlAttributes));
        }

        public static MvcHtmlString Image<TController>(this HtmlHelper html, Expression<Func<TController, ActionResult>> action, IDictionary<string, object> routeValues, IDictionary<string, object> htmlAttributes)
        {
            if (html == null) throw new ArgumentNullException("html");

            var combinedRouteValues = html.ViewContext.Controller.GetCombinedRouteValuesWithState(action, routeValues);

            return ImageExtensions.Image(html, combinedRouteValues, htmlAttributes);
        }

        public static MvcHtmlString Image(this HtmlHelper html, IDictionary<string, object> routeValues, IDictionary<string, object> htmlAttributes)
        {
            if (html == null) throw new ArgumentNullException("html");

            var routeValuesDictionary = new RouteValueDictionary(routeValues);

            var stateService = html.GetService<IStateService>(false);
            if (stateService != null)
                stateService.SaveObjectsState(routeValuesDictionary);

            var url = UrlHelper.GenerateUrl(null, null, null, routeValuesDictionary, html.RouteCollection, html.ViewContext.RequestContext, true);


            TagBuilder builder = new TagBuilder("img");
            builder.MergeAttribute("src", url);

            if (htmlAttributes != null)
                builder.MergeAttributes(htmlAttributes);

            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }
    }
}